package com.xbongbong.process.data;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.executor.command.FormDataServiceFactory;
import com.xbongbong.executor.command.FormDataUpdateServiceFactory;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.domain.entity.PaasFormExplainEntity;
import com.xbongbong.paas.domain.entity.PaasProcessDataEntity;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.OtherExpenseSheetTypeEnum;
import com.xbongbong.paas.enums.OtherIncomeSheetTypeEnum;
import com.xbongbong.paas.enums.PaySheetTypeEnum;
import com.xbongbong.paas.enums.PaymentSheetTypeEnum;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.FormDataHelp;
import com.xbongbong.paas.model.PaasFormExplainModel;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.dto.FormDataAddDTO;
import com.xbongbong.paas.pojo.dto.FormDataUpdateDTO;
import com.xbongbong.paas.pojo.dto.ProcessDataAddFormDataDTO;
import com.xbongbong.paas.pojo.dto.ProcessDataUpdateFormDataDTO;
import com.xbongbong.paas.pojo.vo.AfterSaveVO;
import com.xbongbong.paas.pojo.vo.ProcessDataAddFormDataVO;
import com.xbongbong.paas.pojo.vo.ProcessDataUpdateFormDataVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.JsonDataUtil;
import com.xbongbong.paas.toolbox.util.JsonHelperUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.XbbResponse;
import com.xbongbong.parent.interfaces.FormDataService;
import com.xbongbong.parent.interfaces.FormDataUpdateService;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.SaasMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.formdata.pojo.vo.BeforeSaveVO;
import com.xbongbong.pro.formdata.pojo.vo.BeforeUpdateVO;
import com.xbongbong.pro.formdata.pojo.vo.SaveVO;
import com.xbongbong.pro.formdata.pojo.vo.UpdateVO;
import com.xbongbong.pro.process.pojo.dto.ProcessSaveDataDTO;
import com.xbongbong.pro.user.pojo.ReturnUserAndDepartmentPojo;
import com.xbongbong.process.feign.DistributorProcessFeign;
import com.xbongbong.saas.constant.StockConstant;
import com.xbongbong.saas.domain.entity.WorkOrderEntity;
import com.xbongbong.saas.domain.entity.WorkOrderFormEntity;
import com.xbongbong.saas.domain.entity.ext.WorkOrderExplainEntityExt;
import com.xbongbong.saas.domain.entity.ext.WorkOrderFormEntityExt;
import com.xbongbong.saas.enums.InstockTypeEnum;
import com.xbongbong.saas.enums.OutstockTypeEnum;
import com.xbongbong.saas.enums.WorkOrderStatusEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.CompetitorEnum;
import com.xbongbong.saas.enums.business.InstockEnum;
import com.xbongbong.saas.enums.business.OtherExpenseEnum;
import com.xbongbong.saas.enums.business.OtherIncomeEnum;
import com.xbongbong.saas.enums.business.OutstockEnum;
import com.xbongbong.saas.enums.business.PaySheetEnum;
import com.xbongbong.saas.enums.business.PaymentSheetEnum;
import com.xbongbong.saas.model.WorkOrderExplainModel;
import com.xbongbong.saas.model.WorkOrderFormModel;
import com.xbongbong.saas.model.WorkOrderModel;
import com.xbongbong.util.OwnerIdAndCoUserIdUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;

/**
 * 新建审批通过或者编辑审批
 * @author 吴峰
 * @date 2022/01/06 15:33
 */
@Service("processDataSynchronizedFormService")
public class ProcessDataSynchronizedFormServiceImpl implements ProcessDataSynchronizedFormService {

    private static final Logger LOG = LoggerFactory.getLogger(ProcessDataSynchronizedFormServiceImpl.class);
    @Resource
    private WorkOrderExplainModel workOrderExplainModel;
    @Resource
    private PaasFormExplainModel paasFormExplainModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private WorkOrderFormModel workOrderFormModel;
    @Resource
    private FormDataServiceFactory formDataServiceFactory;
    @Resource
    private FormDataUpdateServiceFactory formDataUpdateServiceFactory;
    @Resource
    private FormDataHelp formDataHelp;
    @Resource
    private WorkOrderModel workOrderModel;
    @Resource
    private DistributorProcessFeign distributorProcessFeign;

    @Override
    public ProcessDataAddFormDataVO processDataAddFormData(ProcessDataAddFormDataDTO processDataAddFormDataDTO) throws XbbException {
        // 更新流程状态和流程负责人
        ProcessDataAddFormDataVO processDataAddFormDataVO = new ProcessDataAddFormDataVO();
        try {
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            if (StringUtil.isEmpty(processDataAddFormDataDTO.getOwnerId())) {
                processDataAddFormDataDTO.setOwnerId(processDataAddFormDataDTO.getCreatorId());
            }
            BeanUtil.copyProperties(processDataAddFormDataDTO, paasFormDataEntity);
            if ( processDataAddFormDataDTO.getFlowStatus().equals(FlowStatusEnum.PASS.getType()) ) {
                // 流程通过时，将流程数据同步进表单数据
                paasFormDataEntity.setData(JsonHelperUtil.parseObject(processDataAddFormDataDTO.getData()));
            }
            paasFormDataEntity.setCorpid(processDataAddFormDataDTO.getCorpid());
            paasFormDataEntity.setFlowStatus(processDataAddFormDataDTO.getFlowStatus());
            paasFormDataEntity.setCreatorId(processDataAddFormDataDTO.getCreatorId());
            paasFormDataEntity.setDepartmentId(processDataAddFormDataDTO.getDepartmentId());

            PaasFormExplainEntity paasFormExplainEntity = new PaasFormExplainEntity();
            if ( Objects.equals(processDataAddFormDataDTO.getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode()) ) {
                WorkOrderExplainEntityExt workOrderExplainEntityExt = workOrderExplainModel.getByFormId(paasFormDataEntity.getFormId(), processDataAddFormDataDTO.getCorpid());
                BeanUtil.copyProperties(workOrderExplainEntityExt, paasFormExplainEntity);
            }/* else if ( Objects.equals(processDataAddFormDataDTO.getBusinessType(), XbbRefTypeEnum.PAY_SHEET.getCode()) || Objects.equals(processDataAddFormDataDTO.getBusinessType(), XbbRefTypeEnum.PAYMENT_SHEET.getCode()) ) {
                paasFormExplainEntity = paasFormExplainModel.getByBusinessType(processDataAddFormDataDTO.getBusinessType(), processDataAddFormDataDTO.getCorpid());
            }*/ else {
                paasFormExplainEntity = paasFormExplainModel.getByFormId(paasFormDataEntity.getFormId(), processDataAddFormDataDTO.getCorpid());
            }
            List<FieldAttrEntity> fieldList = JSON.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            Map<String, FieldAttrEntity> explainMap = new HashMap<>(fieldList.size());
            fieldList.forEach(item->{explainMap.put(item.getAttr(), item);});
            if ( Objects.equals(processDataAddFormDataDTO.getBusinessType(), XbbRefTypeEnum.PAY_SHEET.getCode()) ) {
                //付款单
                JSONObject data = JSONObject.parseObject(processDataAddFormDataDTO.getData());
                String paySheetType = JsonDataUtil.getStringFromFormData(data, PaySheetEnum.PAY_SHEET_TYPE.getAttr());
                PaySheetTypeEnum paySheetTypeEnum = PaySheetTypeEnum.getByCode(paySheetType);
                Integer businessType = paySheetTypeEnum.getBusinessType();
                //将付款单流程数据插入到表单数据
                processDataAddFormData4Sheet(processDataAddFormDataDTO, paasFormDataEntity, explainMap, data, businessType, fieldList);
            } else if ( Objects.equals(processDataAddFormDataDTO.getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode()) ) {
                FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
                BeanUtil.copyProperties(processDataAddFormDataDTO, formDataAddDTO);
                formDataAddDTO.setDataList(JSONObject.parseObject(processDataAddFormDataDTO.getData()));
                formDataAddDTO.setSaasNeedRedundantAttrPoJo(processDataAddFormDataDTO.getSaasNeedRedundantAttrPoJo());
                formDataAddDTO.setExplainMap(explainMap);
                WorkOrderFormEntityExt workOrderFormEntityExt = workOrderFormModel.getByKey(formDataAddDTO.getFormId(), processDataAddFormDataDTO.getCorpid());
                if ( Objects.isNull(workOrderFormEntityExt) ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
                }
                WorkOrderEntity workOrderEntity = new WorkOrderEntity();
                workOrderEntity.setTemplateId(workOrderFormEntityExt.getTemplateId());
                workOrderEntity.setMenuId(workOrderFormEntityExt.getMenuId());
                BeanUtil.copyProperties(paasFormDataEntity, workOrderEntity);
                workOrderEntity.setStatus(WorkOrderStatusEnum.UNACCEPTED.getCode());
                FormDataService abstractFormDataService = formDataServiceFactory.getFormDataService(formDataAddDTO.getBusinessType(), formDataAddDTO.getSaasMark());
                BeforeSaveVO beforeSaveVO = new BeforeSaveVO();
                beforeSaveVO.setWorkOrderEntity(workOrderEntity);
                beforeSaveVO.setWorkOrderFormEntityExt(workOrderFormEntityExt);
                beforeSaveVO.setSaasNeedRedundantAttrPojo(processDataAddFormDataDTO.getSaasNeedRedundantAttrPoJo());
                beforeSaveVO.setExplainMap(explainMap);
                beforeSaveVO.setExplainList(fieldList);
                beforeSaveVO.setNoApprovalRequired(1);
                SaveVO saveVO = abstractFormDataService.save(formDataAddDTO, beforeSaveVO, workOrderFormEntityExt, workOrderEntity);
                abstractFormDataService.afterSave(formDataAddDTO, beforeSaveVO, saveVO, workOrderFormEntityExt, workOrderEntity);
            } else if ( Objects.equals(processDataAddFormDataDTO.getBusinessType(), XbbRefTypeEnum.PAYMENT_SHEET.getCode()) ) {
                JSONObject data = JSONObject.parseObject(processDataAddFormDataDTO.getData());
                String paymentSheetType = JsonDataUtil.getStringFromFormData(data, PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr());
                PaymentSheetTypeEnum paymentSheetTypeEnum = PaymentSheetTypeEnum.getByCode(paymentSheetType);
                Integer businessType = paymentSheetTypeEnum.getBusinessType();
                //将回款单流程数据插入到表单数据
                processDataAddFormData4Sheet(processDataAddFormDataDTO, paasFormDataEntity, explainMap, data, businessType, fieldList);
            } else if ( Objects.equals(processDataAddFormDataDTO.getBusinessType(), XbbRefTypeEnum.OTHER_INCOME.getCode()) ) {
                JSONObject data = JSONObject.parseObject(processDataAddFormDataDTO.getData());
                String sheetType = JsonDataUtil.getStringFromFormData(data, OtherIncomeEnum.SHEET_TYPE_OTHER.getAttr());
                OtherIncomeSheetTypeEnum sheetTypeEnum = OtherIncomeSheetTypeEnum.getByCode(sheetType);
                Integer businessType = sheetTypeEnum.getBusinessType();
                //将其他收入单流程数据插入到表单数据
                processDataAddFormData4Sheet(processDataAddFormDataDTO, paasFormDataEntity, explainMap, data, businessType, fieldList);
            } else if ( Objects.equals(processDataAddFormDataDTO.getBusinessType(), XbbRefTypeEnum.OTHER_EXPENSE.getCode()) ) {
                JSONObject data = JSONObject.parseObject(processDataAddFormDataDTO.getData());
                String sheetType = JsonDataUtil.getStringFromFormData(data, OtherExpenseEnum.SHEET_TYPE_OTHER.getAttr());
                OtherExpenseSheetTypeEnum sheetTypeEnum = OtherExpenseSheetTypeEnum.getByCode(sheetType);
                Integer businessType = sheetTypeEnum.getBusinessType();
                //将其他支出单流程数据插入到表单数据
                processDataAddFormData4Sheet(processDataAddFormDataDTO, paasFormDataEntity, explainMap, data, businessType, fieldList);
            } else {
                FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
                BeanUtil.copyProperties(processDataAddFormDataDTO, formDataAddDTO);
                if ( !Objects.equals(processDataAddFormDataDTO.getSubBusinessType(), XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode()) || !Objects.equals(processDataAddFormDataDTO.getSubBusinessType(), XbbRefTypeEnum.CLUE_PUBLIC.getCode())) {
                    formDataAddDTO.setOwnerId(Collections.singletonList(new ReturnUserAndDepartmentPojo(processDataAddFormDataDTO.getOwnerId())));
                }
                JSONObject data = JSONObject.parseObject(processDataAddFormDataDTO.getData());
                formDataAddDTO.setDataList(data);
                formDataAddDTO.setSaasNeedRedundantAttrPoJo(processDataAddFormDataDTO.getSaasNeedRedundantAttrPoJo());
                formDataAddDTO.setExplainMap(explainMap);
                OwnerIdAndCoUserIdUtil.setOwnIdAndCoUserId(data, formDataAddDTO, null);
                PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formDataAddDTO.getFormId(), formDataAddDTO.getCorpid());
                if ( paasFormEntityExt == null ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
                }
                formDataAddDTO.setProcessCreatorId(processDataAddFormDataDTO.getCreatorId());
                if(Objects.equals(processDataAddFormDataDTO.getBusinessType(),XbbRefTypeEnum.COMPETITOR.getCode())){
                    formDataAddDTO.setVisbleUser(data.getJSONArray(CompetitorEnum.VISBLE_USER.getAttr()));
                    formDataAddDTO.setVisbleDept(data.getJSONArray(CompetitorEnum.VISBLE_DEPT.getAttr()));
                }
                if (StockConstant.OTHER_STOCK_TYPE_LIST.contains(processDataAddFormDataDTO.getBusinessType())) {
                    Integer stockBusinessType = null;
                    if (Objects.equals(processDataAddFormDataDTO.getBusinessType(), XbbRefTypeEnum.OTHER_INSTOCK.getCode())) {
                        Integer type = data.getInteger(InstockEnum.TYPE.getAttr());
                        InstockTypeEnum instockTypeEnum = InstockTypeEnum.getByCode(type);
                        stockBusinessType = instockTypeEnum.getStockBusinessType();
                    } else if (Objects.equals(processDataAddFormDataDTO.getBusinessType(), XbbRefTypeEnum.OTHER_OUTSTOCK.getCode())) {
                        Integer type = data.getInteger(OutstockEnum.TYPE.getAttr());
                        OutstockTypeEnum outstockTypeEnum = OutstockTypeEnum.getByCode(type);
                        stockBusinessType = outstockTypeEnum.getStockBusinessType();
                    }
                    PaasFormEntityExt realStockFormEntity = paasFormModel.getByBusinessType(stockBusinessType, processDataAddFormDataDTO.getCorpid());
                    if (Objects.isNull(realStockFormEntity)) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
                    }
                    formDataAddDTO.setAppId(realStockFormEntity.getAppId());
                    formDataAddDTO.setMenuId(realStockFormEntity.getMenuId());
                    formDataAddDTO.setFormId(realStockFormEntity.getId());
                    formDataAddDTO.setBusinessType(realStockFormEntity.getBusinessType());
                    formDataAddDTO.setSubBusinessType(realStockFormEntity.getBusinessType());
                    paasFormDataEntity.setAppId(realStockFormEntity.getAppId());
                    paasFormDataEntity.setMenuId(realStockFormEntity.getMenuId());
                    paasFormDataEntity.setFormId(realStockFormEntity.getId());
                    paasFormEntityExt = realStockFormEntity;
                }
                AfterSaveVO afterSaveVO;
                if (Objects.equals(paasFormExplainEntity.getDistributorMark(), DistributorMarkEnum.DISTRIBUTOR.getCode())){
                    // TODO 经销商无法调到
                    Locale locale = LocaleContextHolder.getLocale();
                    String lang = locale.toString();
                    ProcessSaveDataDTO processSaveDataDTO = new ProcessSaveDataDTO(formDataAddDTO, paasFormDataEntity, processDataAddFormDataDTO.getPlatform(), processDataAddFormDataDTO.getLoginUser());
                    XbbResponse<AfterSaveVO> xbbResponse = distributorProcessFeign.processAddFormData(processSaveDataDTO, lang);
                    if (xbbResponse.isSuccess()) {
                        afterSaveVO = xbbResponse.getResult();
                        paasFormDataEntity.setId(afterSaveVO.getFormDataId());
                    } else {
                        throw new XbbException(xbbResponse.getCode(), xbbResponse.getMsg());
                    }
 //                        // 业务规则逻辑
//                        String businessRules = paasFormEntityExt.getBusinessRules();
//                        if (Objects.equals("1", businessRules)) {
//                            ActiveRuleDTO activeRuleDTO = new ActiveRuleDTO();
//                            BeanUtil.copyProperties(processDataAddFormDataDTO, activeRuleDTO);
//                            activeRuleDTO.setDataId(paasFormDataEntity.getId());
//                            activeRuleDTO.setExplainList(fieldList);
//                            long now = DateUtil.getInt();
//                            paasFormDataEntity.setAddTime(now);
//                            paasFormDataEntity.setUpdateTime(now);
//                            PaasFormDataEntity newFormData = proModelService.getFormDataEntity(processDataAddFormDataDTO.getCorpid(), formDataAddDTO.getSaasMark(),formDataAddDTO.getBusinessType(), afterSaveVO.getFormDataId());
//                            IndexTypeEnum indexTypeEnum = EsUtil.getSubFormIndexTypeEnum(formDataAddDTO.getSaasMark(), formDataAddDTO.getBusinessType());
//                            paasFormSubDataModel.transferSubForm(newFormData, indexTypeEnum);
//                            activeRuleDTO.setPaasFormDataEntity(newFormData);
//                            formDataActiveRuleHelp.activeRule(activeRuleDTO);
//                        }
                }else {
                    FormDataService abstractFormDataService = formDataServiceFactory.getFormDataService(formDataAddDTO.getBusinessType(), formDataAddDTO.getSaasMark());
                    BeforeSaveVO beforeSaveVO = new BeforeSaveVO();
                    beforeSaveVO.setPaasFormDataEntity(paasFormDataEntity);
                    beforeSaveVO.setPaasFormEntityExt(paasFormEntityExt);
                    beforeSaveVO.setSaasNeedRedundantAttrPojo(processDataAddFormDataDTO.getSaasNeedRedundantAttrPoJo());
                    beforeSaveVO.setExplainMap(explainMap);
                    beforeSaveVO.setExplainList(fieldList);
                    beforeSaveVO.setNoApprovalRequired(1);
                    SaveVO saveVO = abstractFormDataService.save(formDataAddDTO, beforeSaveVO, paasFormEntityExt, paasFormDataEntity);
                    abstractFormDataService.afterSave(formDataAddDTO, beforeSaveVO, saveVO, paasFormEntityExt, paasFormDataEntity);

                }

            }
            processDataAddFormDataVO.setFormDataId(paasFormDataEntity.getId());
        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasFormData.updateFlowStatus数据库更新流程状态和流程负责人操作出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return processDataAddFormDataVO;
    }



    @Override
    public ProcessDataUpdateFormDataVO processDataUpdateFormData(ProcessDataUpdateFormDataDTO processDataUpdateFormDataDTO) throws XbbException {
        // 更新流程状态和流程负责人
        ProcessDataUpdateFormDataVO processDataUpdateFormDataVO = new ProcessDataUpdateFormDataVO();
        try {
            PaasFormDataEntity paasFormDataEntity = new PaasFormDataEntity();
            if ( processDataUpdateFormDataDTO.getOwnerId() == null ) {
                processDataUpdateFormDataDTO.setOwnerId("");
            }
            JSONObject data = JsonHelperUtil.parseObject(processDataUpdateFormDataDTO.getData());
            if (processDataUpdateFormDataDTO.getFlowStatus().equals(FlowStatusEnum.PASS.getType())) {
                // 流程通过时，将流程数据同步进表单数据
                paasFormDataEntity.setData(data);
            }
            paasFormDataEntity.setId(processDataUpdateFormDataDTO.getFormDataId());
            paasFormDataEntity.setCorpid(processDataUpdateFormDataDTO.getCorpid());
            paasFormDataEntity.setFlowStatus(processDataUpdateFormDataDTO.getFlowStatus());
            paasFormDataEntity.setSerialNo(processDataUpdateFormDataDTO.getSerialNo());
            paasFormDataEntity.setOwnerId(processDataUpdateFormDataDTO.getOwnerId());
            paasFormDataEntity.setDepartmentId(processDataUpdateFormDataDTO.getDepartmentId());
            paasFormDataEntity.setFormId(processDataUpdateFormDataDTO.getFormId());
            paasFormDataEntity.setCreatorId(processDataUpdateFormDataDTO.getCreatorId());
            FormDataUpdateDTO formDataUpdateDTO = new FormDataUpdateDTO();
            BeanUtil.copyProperties(processDataUpdateFormDataDTO, formDataUpdateDTO);
            formDataUpdateDTO.setProcessCreatorId(processDataUpdateFormDataDTO.getCreatorId());
            formDataUpdateDTO.setIsFromProcess(1);
            if (!Objects.equals(processDataUpdateFormDataDTO.getSubBusinessType(), XbbRefTypeEnum.CUSTOMER_PUBLIC.getCode()) || !Objects.equals(processDataUpdateFormDataDTO.getSubBusinessType(), XbbRefTypeEnum.CLUE_PUBLIC.getCode())) {
                formDataUpdateDTO.setOwnerId(Collections.singletonList(new ReturnUserAndDepartmentPojo(processDataUpdateFormDataDTO.getOwnerId())));
            }
            formDataUpdateDTO.setDataId(processDataUpdateFormDataDTO.getFormDataId());
            PaasFormDataEntity oldPaasFormDataEntity = formDataHelp.getFormDataEntity(formDataUpdateDTO.getCorpid(), formDataUpdateDTO.getSaasMark(), formDataUpdateDTO.getBusinessType(), formDataUpdateDTO.getDataId());
            PaasFormExplainEntity paasFormExplainEntity = new PaasFormExplainEntity();
            if ( Objects.equals(processDataUpdateFormDataDTO.getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode()) ) {
                WorkOrderExplainEntityExt workOrderExplainEntityExt = workOrderExplainModel.getByFormId(processDataUpdateFormDataDTO.getFormId(), processDataUpdateFormDataDTO.getCorpid());
                BeanUtil.copyProperties(workOrderExplainEntityExt, paasFormExplainEntity);
            }/* else if ( Objects.equals(processDataUpdateFormDataDTO.getBusinessType(), XbbRefTypeEnum.PAY_SHEET.getCode()) || Objects.equals(processDataUpdateFormDataDTO.getBusinessType(), XbbRefTypeEnum.PAYMENT_SHEET.getCode()) ) {
                paasFormExplainEntity = paasFormExplainModel.getByBusinessType(processDataUpdateFormDataDTO.getBusinessType(), processDataUpdateFormDataDTO.getCorpid());
            } */else {
                paasFormExplainEntity = paasFormExplainModel.getByFormId(processDataUpdateFormDataDTO.getFormId(), processDataUpdateFormDataDTO.getCorpid());
            }
            PaasFormEntityExt paasFormEntityExt = new PaasFormEntityExt();
            WorkOrderFormEntity workOrderFormEntity = new WorkOrderFormEntity();
            if ( Objects.equals(processDataUpdateFormDataDTO.getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode()) ) {
                workOrderFormEntity = workOrderFormModel.getByKey(processDataUpdateFormDataDTO.getFormId(), processDataUpdateFormDataDTO.getCorpid());
                if ( workOrderFormEntity == null ) {
                    throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
                }
                BeanUtil.copyProperties(workOrderFormEntity, paasFormEntityExt);
                paasFormEntityExt.setSaasMark(SaasMarkEnum.SAAS.getCode());
                paasFormEntityExt.setBusinessType(XbbRefTypeEnum.WORK_ORDER.getCode());
            } else {
                paasFormEntityExt = paasFormModel.getByKey(processDataUpdateFormDataDTO.getFormId(), processDataUpdateFormDataDTO.getCorpid());
            }
            if ( paasFormEntityExt == null ) {
                throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
            }
            List<FieldAttrEntity> fieldList = JSON.parseArray(paasFormExplainEntity.getExplains(), FieldAttrEntity.class);
            Map<String, FieldAttrEntity> explainMap = new HashMap<>(fieldList.size());
            fieldList.forEach(item->{explainMap.put(item.getAttr(), item);});
            formDataUpdateDTO.setExplainMap(explainMap);
            String formName = paasFormEntityExt.getName();
            formDataUpdateDTO.setProcessCreatorId(processDataUpdateFormDataDTO.getCreatorId());
            if ( Objects.equals(processDataUpdateFormDataDTO.getBusinessType(), XbbRefTypeEnum.PAYMENT_SHEET.getCode()) ) {
                String paymentSheetType = JsonDataUtil.getStringFromFormData(paasFormDataEntity.getData(), PaymentSheetEnum.PAYMENT_SHEET_TYPE.getAttr());
                PaymentSheetTypeEnum paymentSheetTypeEnum = PaymentSheetTypeEnum.getByCode(paymentSheetType);
                formDataUpdateDTO.setBusinessType(paymentSheetTypeEnum.getBusinessType());
                PaasProcessDataEntity paasProcessDataEntity = new PaasProcessDataEntity();
                paasProcessDataEntity.setCorpid(processDataUpdateFormDataDTO.getCorpid());
                paasProcessDataEntity.setSaasMark(1);
                paasProcessDataEntity.setBusinessType(paymentSheetTypeEnum.getBusinessType());
                paasProcessDataEntity.setFormDataId(oldPaasFormDataEntity.getId());
                formDataHelp.updateFormDataStatus(paasProcessDataEntity, FlowStatusEnum.IN_APPROVAL.getType());
            } else if ( Objects.equals(processDataUpdateFormDataDTO.getBusinessType(), XbbRefTypeEnum.PAY_SHEET.getCode()) ) {
                String paySheetType = JsonDataUtil.getStringFromFormData(paasFormDataEntity.getData(), PaySheetEnum.PAY_SHEET_TYPE.getAttr());
                PaySheetTypeEnum paySheetTypeEnum = PaySheetTypeEnum.getByCode(paySheetType);
                formDataUpdateDTO.setBusinessType(paySheetTypeEnum.getBusinessType());
                PaasProcessDataEntity paasProcessDataEntity = new PaasProcessDataEntity();
                paasProcessDataEntity.setCorpid(processDataUpdateFormDataDTO.getCorpid());
                paasProcessDataEntity.setSaasMark(1);
                paasProcessDataEntity.setBusinessType(paySheetTypeEnum.getBusinessType());
                paasProcessDataEntity.setFormDataId(oldPaasFormDataEntity.getId());
                formDataHelp.updateFormDataStatus(paasProcessDataEntity, FlowStatusEnum.IN_APPROVAL.getType());
            }
            Integer updateLine = 0;
            if ( Objects.equals(formDataUpdateDTO.getBusinessType(), XbbRefTypeEnum.WORK_ORDER.getCode()) ) {
                WorkOrderEntity oldWorkOrderEntity = workOrderModel.getByKey(formDataUpdateDTO.getDataId(), processDataUpdateFormDataDTO.getCorpid());
                // 不给默认值
                WorkOrderEntity workOrderEntity = new WorkOrderEntity(null);
                BeanUtil.copyProperties(paasFormDataEntity, workOrderEntity);
                FormDataUpdateService abstractFormDataService = formDataUpdateServiceFactory.getFormDataUpdateService(formDataUpdateDTO.getBusinessType(), formDataUpdateDTO.getSaasMark());
                BeforeUpdateVO beforeSaveVO = new BeforeUpdateVO();
                beforeSaveVO.setWorkOrderEntity(workOrderEntity);
                beforeSaveVO.setOldWorkOrderEntity(oldWorkOrderEntity);
                beforeSaveVO.setSaasNeedRedundantAttrPojo(formDataUpdateDTO.getSaasNeedRedundantAttrPoJo());
                beforeSaveVO.setExplainMap(explainMap);
                beforeSaveVO.setExplainList(fieldList);
                beforeSaveVO.setNoApprovalRequired(1);
                beforeSaveVO.setWorkOrderFormEntity(workOrderFormEntity);
                UpdateVO saveVO = abstractFormDataService.update(formDataUpdateDTO, beforeSaveVO, workOrderFormEntity, workOrderEntity, oldWorkOrderEntity);
                abstractFormDataService.afterSave(formDataUpdateDTO, beforeSaveVO, saveVO, workOrderFormEntity, workOrderEntity, oldWorkOrderEntity);
                updateLine = saveVO.getUpdateLine();
            } else {
                OwnerIdAndCoUserIdUtil.setOwnIdAndCoUserId(paasFormDataEntity.getData(), null, formDataUpdateDTO);
                if (StockConstant.OTHER_STOCK_TYPE_LIST.contains(processDataUpdateFormDataDTO.getBusinessType())) {
                    Integer stockBusinessType = null;
                    if (Objects.equals(processDataUpdateFormDataDTO.getBusinessType(), XbbRefTypeEnum.OTHER_INSTOCK.getCode())) {
                        Integer type = data.getInteger(InstockEnum.TYPE.getAttr());
                        InstockTypeEnum instockTypeEnum = InstockTypeEnum.getByCode(type);
                        stockBusinessType = instockTypeEnum.getStockBusinessType();
                    } else if (Objects.equals(processDataUpdateFormDataDTO.getBusinessType(), XbbRefTypeEnum.OTHER_OUTSTOCK.getCode())) {
                        Integer type =data.getInteger(OutstockEnum.TYPE.getAttr());
                        OutstockTypeEnum outstockTypeEnum = OutstockTypeEnum.getByCode(type);
                        stockBusinessType = outstockTypeEnum.getStockBusinessType();
                    }
                    PaasFormEntityExt realStockFormEntity = paasFormModel.getByBusinessType(stockBusinessType, processDataUpdateFormDataDTO.getCorpid());
                    if (Objects.isNull(realStockFormEntity)) {
                        throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
                    }
                    formDataUpdateDTO.setAppId(realStockFormEntity.getAppId());
                    formDataUpdateDTO.setMenuId(realStockFormEntity.getMenuId());
                    formDataUpdateDTO.setFormId(realStockFormEntity.getId());
                    formDataUpdateDTO.setBusinessType(realStockFormEntity.getBusinessType());
                    formDataUpdateDTO.setSubBusinessType(realStockFormEntity.getBusinessType());
                    paasFormDataEntity.setAppId(realStockFormEntity.getAppId());
                    paasFormDataEntity.setMenuId(realStockFormEntity.getMenuId());
                    paasFormDataEntity.setFormId(realStockFormEntity.getId());
                    oldPaasFormDataEntity.setAppId(realStockFormEntity.getAppId());
                    oldPaasFormDataEntity.setMenuId(realStockFormEntity.getMenuId());
                    oldPaasFormDataEntity.setFormId(realStockFormEntity.getId());
                    paasFormEntityExt = realStockFormEntity;
                }
                AfterSaveVO afterSaveVO;
                if (Objects.equals(paasFormExplainEntity.getDistributorMark(), 1)) {
                    // TODO 经销商无法调到
                    Locale locale = LocaleContextHolder.getLocale();
                    String lang = locale.toString();
                    ProcessSaveDataDTO processSaveDataDTO = new ProcessSaveDataDTO(formDataUpdateDTO, paasFormDataEntity, oldPaasFormDataEntity, processDataUpdateFormDataDTO.getPlatform(), processDataUpdateFormDataDTO.getLoginUser());
                    XbbResponse<AfterSaveVO> xbbResponse = distributorProcessFeign.processUpdateFormData(processSaveDataDTO, lang);
                    if (xbbResponse.isSuccess()) {
                        afterSaveVO = xbbResponse.getResult();
                    } else {
                        throw new XbbException(xbbResponse.getCode(), xbbResponse.getMsg());
                    }
                } else {
                    FormDataUpdateService abstractFormDataService = formDataUpdateServiceFactory.getFormDataUpdateService(formDataUpdateDTO.getBusinessType(), formDataUpdateDTO.getSaasMark());
                    BeforeUpdateVO beforeSaveVO = new BeforeUpdateVO();
                    beforeSaveVO.setPaasFormDataEntity(paasFormDataEntity);
                    beforeSaveVO.setOldPaasFormData(oldPaasFormDataEntity);
                    beforeSaveVO.setPaasFormEntityExt(paasFormEntityExt);
                    beforeSaveVO.setSaasNeedRedundantAttrPojo(formDataUpdateDTO.getSaasNeedRedundantAttrPoJo());
                    beforeSaveVO.setExplainMap(explainMap);
                    beforeSaveVO.setExplainList(fieldList);
                    beforeSaveVO.setNoApprovalRequired(1);
                    UpdateVO saveVO = abstractFormDataService.update(formDataUpdateDTO, beforeSaveVO, paasFormEntityExt, paasFormDataEntity, oldPaasFormDataEntity);
                    formDataUpdateDTO.setCommitUserId(processDataUpdateFormDataDTO.getCreatorId());
                    abstractFormDataService.afterSave(formDataUpdateDTO, beforeSaveVO, saveVO, paasFormEntityExt, paasFormDataEntity, oldPaasFormDataEntity);
                    updateLine = saveVO.getUpdateLine();
                }

            }
            // paas的逻辑 paasFormDataModel.processDataUpdateFormData(paasFormDataEntity)
            processDataUpdateFormDataVO.setFormDataId(processDataUpdateFormDataDTO.getFormDataId());

        } catch (XbbException e) {
            throw e;
        } catch (Exception e) {
            LOG.error("paasFormData.updateFlowStatus数据库更新流程状态和流程负责人操作出错", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, SystemErrorCodeEnum.API_ERROR_100001.getMsg());
        }
        return processDataUpdateFormDataVO;
    }


    /**
     * 将回/付款单流程数据插入到表单数据
     * @param processDataAddFormDataDTO 流程dto
     * @param paasFormDataEntity 实体
     * @param explainMap 字段解释map
     * @param data 数据data
     * @param businessType 回/付款单类型（已转换为具体类型的businessType）
     * @throws XbbException
     * @author zcp
     * @since v1.0
     * @version v1.0
     */
    private void processDataAddFormData4Sheet(ProcessDataAddFormDataDTO processDataAddFormDataDTO, PaasFormDataEntity paasFormDataEntity, Map<String, FieldAttrEntity> explainMap,
                                              JSONObject data, Integer businessType, List<FieldAttrEntity> fieldList) throws XbbException {
        SaasNeedRedundantAttrPojo saasNeedRedundantAttrPoJo = processDataAddFormDataDTO.getSaasNeedRedundantAttrPoJo();
        FormDataAddDTO formDataAddDTO = new FormDataAddDTO();
        BeanUtil.copyProperties(processDataAddFormDataDTO, formDataAddDTO);
        formDataAddDTO.setBusinessType(businessType);
        formDataAddDTO.setDataList(data);
        formDataAddDTO.setSaasNeedRedundantAttrPoJo(saasNeedRedundantAttrPoJo);
        formDataAddDTO.setExplainMap(explainMap);
        OwnerIdAndCoUserIdUtil.setOwnIdAndCoUserId(data, formDataAddDTO, null);
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByKey(formDataAddDTO.getFormId(), formDataAddDTO.getCorpid());
        if ( paasFormEntityExt == null ) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
        }
        if (saasNeedRedundantAttrPoJo != null) {
            //处理amoutDetail
            JSONArray amountDetailTemp = saasNeedRedundantAttrPoJo.getAmountDetail();
            if (CollectionUtils.isNotEmpty(amountDetailTemp)) {
                JSONArray amountDetail = new JSONArray();
                for (Object object : amountDetailTemp) {
                    JSONObject jsonObject1 = JSONObject.parseObject(JSONObject.toJSONString(object));
                    amountDetail.add(jsonObject1);
                }
                formDataAddDTO.setAmountDetail(amountDetail);
            }
        }
        formDataAddDTO.setProcessCreatorId(processDataAddFormDataDTO.getCreatorId());
        FormDataService abstractFormDataService = formDataServiceFactory.getFormDataService(formDataAddDTO.getBusinessType(), formDataAddDTO.getSaasMark());
        BeforeSaveVO beforeSaveVO = new BeforeSaveVO();
        beforeSaveVO.setPaasFormDataEntity(paasFormDataEntity);
        beforeSaveVO.setPaasFormEntityExt(paasFormEntityExt);
        beforeSaveVO.setSaasNeedRedundantAttrPojo(processDataAddFormDataDTO.getSaasNeedRedundantAttrPoJo());
        beforeSaveVO.setExplainMap(explainMap);
        beforeSaveVO.setExplainList(fieldList);
        beforeSaveVO.setNoApprovalRequired(1);
        SaveVO saveVO = abstractFormDataService.save(formDataAddDTO, beforeSaveVO, paasFormEntityExt, paasFormDataEntity);
        abstractFormDataService.afterSave(formDataAddDTO, beforeSaveVO, saveVO, paasFormEntityExt, paasFormDataEntity);
    }
}
